//
//  WH_HomeViewController.m
//  App_6.23
//
//  Created by wanghao on 16/6/23.
//  Copyright © 2016年 wanghao. All rights reserved.
//

#import "WH_HomeViewController.h"
#import "WH_HomeTableViewCell.h"
#import "WH_TabHeardView.h"
#import "WH_HeaderView.h"
#import "WH_ClassificationController.h"
#import "WH_ShareOrderController.h"
#import "WH_QuestionViewController.h"
#import "WH_HomeDetailController.h"
#import "WH_Home.h"
#import "WH_NewDetailViewController.h"
#import "WH_Newest.h"

@interface WH_HomeViewController ()<UITableViewDataSource,UITableViewDelegate,WH_TabHeardViewDelegate,WH_HomeTableViewCellDelegate,WH_HeaderViewDelegate,UIScrollViewDelegate>{
    
    WSProgressHUD *hud;
}

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) WH_TabHeardView *myheard;
@property (nonatomic, strong) NSMutableArray *imageArr;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) BOOL isUploading;
@property (nonatomic, strong) NSMutableArray *tempArr;
@property (nonatomic, strong) WH_HeaderView *headerV;

@end

@implementation WH_HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"一元夺宝";
    self.navigationItem.leftBarButtonItem = nil;
    [self rightF];
    [self allocNew];
    [self headerTab];
    hud = [[WSProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];

}

#pragma mark - 公告

- (void)rightF{
    
    UIButton * bButton = [UIButton buttonWithType:UIButtonTypeCustom];
    bButton.backgroundColor = [UIColor clearColor];
    [bButton setImage:[[UIImage imageNamed:@"消息"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    bButton.frame = CGRectMake(0, 0, 25, 25);
    bButton.tintColor = [UIColor blackColor];
    [bButton addTarget:self action:@selector(pushToWeb) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:bButton];
}

- (void)pushToWeb{
    
    WH_QuestionViewController *homeWebVC = [[WH_QuestionViewController alloc] init];
    homeWebVC.numbID = 1;
    [self.navigationController pushViewController:homeWebVC animated:YES];
    
}
#pragma mark - 初始化

-(void)allocNew{
    
    self.dataArr = [NSMutableArray array];
    self.imageArr = [NSMutableArray array];
    self.tempArr = [NSMutableArray array];
    self.headerV = [[WH_HeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*0.06)];
    self.headerV.delegate = self;
    self.headerV.backgroundColor = [UIColor whiteColor];
    self.headerV.alpha = .9;
    [self.headerV createButton];
    [self createTab];
}

-(void)createTab{
    
    self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.rowHeight = SCREEN_WIDTH/2+100;
    self.myTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_myTableView];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.view);
        
    }];

    [self.myTableView registerClass:[WH_HomeTableViewCell class] forCellReuseIdentifier:@"tab"];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerTab)];
    self.myTableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerTab)];
    self.myTableView.mj_footer = footer;
    [self.myTableView.mj_footer setHidden:YES];
    [self.myTableView setHidden:YES];

}

#pragma mark - 网络请求
//轮播图
-(void)postWorking{
    
    NSString *url = @"http://y.bmstorez.com/app.php";
    NSString *body = @"action=index";
    [WH_AppTools postUrl:url body:body result:HXJSON requestStyle:(HXRequestString) headerFile:nil success:^(id result) {
        //NSLog(@"%@",result);
        if (self.isUploading == NO){
            
            [self.imageArr removeAllObjects];
            [self.myheard removeFromSuperview];
        }

        NSDictionary *dic = result;
        NSString *status = [dic objectForKey:@"status"];
        
        NSArray *banner_array = [dic objectForKey:@"banner_array"];
        if ([status isEqualToString:@"success"]) {
            for (NSDictionary *dic in banner_array) {
                
                WH_Home *home = [WH_Home modelWithDictionary:dic];
                [self.imageArr addObject:home.banner_image];
            }
            self.myheard = [[WH_TabHeardView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 150+SCREEN_WIDTH/6+70)];
            self.myheard.delegate = self;
            
            self.myTableView.tableHeaderView = _myheard;
            [self.myTableView setHidden:NO];
            [self.myTableView reloadData];
            [self.myheard createSubViews:self.imageArr];
        }
        

    } failure:^(NSError *error) {
        //[self postWorking];
        NSLog(@"请求失败");

        
    }];
    
}
-(void)postData:(NSInteger)type{
    
    NSString *str = @"http://y.bmstorez.com/app.php";
    
    NSString *body = [NSString stringWithFormat:@"action=index_product&type=%ld&page=%ld",type,self.page];
    
    [WH_AppTools postUrl:str body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        
        if (self.isUploading == NO){
            
            [self.dataArr removeAllObjects];
            
        }

       // NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSArray *product_array = [dic objectForKey:@"product_array"];

        for (NSDictionary *dic in product_array) {
            
            WH_Home *product = [WH_Home modelWithDictionary:dic];
            [self.dataArr addObject:product];
        }
        [self.myTableView reloadData];
        [self.myTableView.mj_footer setHidden:NO];
        [hud dismiss];
        [self endFresh];

        //NSLog(@"%lu",(unsigned long)self.dataArr.count);
    } failure:^(NSError *error) {
        
        NSLog(@"请求失败");

    }];
    
    
}
#pragma mark - 结束刷新

-(void)endFresh{
    
    [self.myTableView.mj_footer endRefreshing];
    [self.myTableView.mj_header endRefreshing];
}
#pragma mark - 刷新&&加载

-(void)headerTab
{
    NSLog(@"下拉");
    self.page = 1;
    self.isUploading = NO;
    [self postData:self.type];
    [self postWorking];

}
-(void)footerTab{
    
    self.isUploading = YES;
    self.page++;

    [self postData:self.type];
    
}
#pragma mark - 点击轮播图跳转

-(void)getTapNumber:(WH_Home *)number{
    
    WH_NewDetailViewController *newDetailVC = [[WH_NewDetailViewController alloc] init];
    newDetailVC.detailNew = number;
    [self.navigationController pushViewController:newDetailVC animated:YES];
    
}

#pragma mark - 点击按钮跳转

-(void)pushToClassification:(NSInteger)buttonTag{
    
    if (buttonTag == 100) {
        
    
        WH_ClassificationController *claC = [[WH_ClassificationController alloc] init];
        [self.navigationController pushViewController:claC animated:YES];
    
    }else if (buttonTag == 101){
        
        WH_ShareOrderController *shareOrder = [[WH_ShareOrderController alloc] init];
        shareOrder.indexShare = 101;
        [self.navigationController pushViewController:shareOrder animated:YES];
        
    }else{
        
        WH_QuestionViewController *question = [[WH_QuestionViewController alloc] init];
        question.numbID = 2;
        [self.navigationController pushViewController:question animated:YES];
        
    }
}
#pragma mark - pushToDetailVC

-(void)pushDetailVC:(WH_Home *)homeModel{

    WH_HomeDetailController *homeDetail = [[WH_HomeDetailController alloc] init];
    
    homeDetail.productID = homeModel.product_id;
    //homeDetail.faceImage = homeModel.product_image;
    //homeDetail.faceTitle = homeModel.product_name;
    [self.navigationController pushViewController:homeDetail animated:YES];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.dataArr.count == 0) {
        return 0;
    }else{
        
        return self.dataArr.count/2;
    }
}

#pragma mark - 自定义tableview的头部区域
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
   
    
    return self.headerV;
    
}

#pragma mark - 人气切换
-(void)changeButton:(NSInteger)numb{
    
    self.page = 1;
    self.type = numb-999;
    [self.dataArr removeAllObjects];
    [self postData:self.type];
    NSLog(@"%ld",self.type);
    [hud showWithString:nil];

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *indexTab = @"tab";
    WH_HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indexTab];
    cell.homeDelegate = self;
    NSMutableArray *tempArray = [NSMutableArray array];
    if (self.dataArr.count != 0) {
        
        for (int i = 0; i < 2; i++) {
            
            [tempArray addObject:[self.dataArr objectAtIndex:indexPath.row*2 +i]];
        }
        cell.cellArr = tempArray;
    }
    
    return cell;
    
}
#pragma mark - scrollDelegate

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    if (scrollView.contentOffset.y > SCREEN_HEIGHT) {
//        
//        UIImageView *imageTop = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-40, SCREEN_HEIGHT-49-40, 40, 40)];
//        imageTop.tag = 4940;
//        imageTop.backgroundColor = [UIColor redColor];
//        [self.view addSubview:imageTop];
//        UITapGestureRecognizer *tapTop = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(topUp)];
//        [imageTop addGestureRecognizer:tapTop];
//    }else{
//        
//        UIImageView *imageV = (UIImageView *)[self.view viewWithTag:4940];
//        [imageV removeFromSuperview];
//    }
//
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
